package com.zzzyh.forumsystemclient.services.impl;

import com.zzzyh.forumsystemclient.services.IVerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    private final RedisTemplate<String, String> redisTemplate;

    // 验证码有效期（分钟）
    private static final long CODE_EXPIRE_MINUTES = 5;

    public VerificationCodeServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String generateCode() {
        // 生成6位随机数字验证码
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    @Override
    public void saveCode(String email, String code) {
        // 保存验证码到Redis，设置过期时间
        redisTemplate.opsForValue().set("verification_code:" + email, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
        log.info("验证码已保存，邮箱: {}, 验证码: {}, 有效期: {}分钟", email, code, CODE_EXPIRE_MINUTES);
    }

    @Override
    public boolean validateCode(String email, String code) {
        String key = "verification_code:" + email;
        String savedCode = redisTemplate.opsForValue().get(key);

        if (savedCode == null) {
            log.warn("验证码已过期或不存在，邮箱: {}", email);
            return false;
        }

        boolean isValid = savedCode.equals(code);
        if (isValid) {
            // 验证成功后删除验证码
            removeCode(email);
            log.info("验证码验证成功，邮箱: {}", email);
        } else {
            log.warn("验证码验证失败，邮箱: {}, 输入验证码: {}, 正确验证码: {}", email, code, savedCode);
        }

        return isValid;
    }

    @Override
    public void removeCode(String email) {
        String key = "verification_code:" + email;
        redisTemplate.delete(key);
        log.info("验证码已删除，邮箱: {}", email);
    }
}
